<template>
  <div class="add-quality-report">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>添加工序报工</span>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="quality-form"
      >
        <el-row :gutter="20">

           <el-col :span="12">
            <el-form-item label="工序编码">
              <el-input placeholder="请输入" v-model="formData.processCode" required>
                <template #suffix>
                  <el-button size="mini" @click="openAssociatedItemDialog1">
                    <i class="el-icon-search"></i>
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工序名称" prop="processName">
              <el-input v-model="formData.processName" placeholder="请输入工序名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="加工顺序" prop="processingOrder">
              <el-input v-model="formData.processingOrder" placeholder="请输入加工顺序" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工艺流程" prop="processFlow">
              <el-input v-model="formData.processFlow" placeholder="请输入工艺流程" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人">
              <el-select v-model="formData.person" placeholder="请输入负责人">
                <el-option label="王浩然" value="王浩然"/>
                <el-option label="张三" value="张三"/>
                <el-option label="李四" value="李四"/>
                <el-option label="李雪妮" value="李雪妮"/>
                <el-option label="赵世豪" value="赵世豪"/>
                <el-option label="张豪" value="张豪"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在部门">
              <el-select v-model="formData.department" placeholder="选择质检部门">
                <el-option label="包装部" value="包装部"/>
                <el-option label="生产部" value="生产部"/>
                <el-option label="酵母部" value="酵母部"/>
                <el-option label="原料部" value="原料部"/>
                <el-option label="发酵部" value="发酵部"/>
                <el-option label="采购部" value="采购部"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报工时间" prop="reportingTime">
              <el-date-picker
                v-model="formData.reportingTime"
                type="datetime"
                placeholder="请选择报工时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="完工数量" prop="quantity">
              <el-input-number 
                v-model="formData.quantity" 
                :min="0"
                style="width: 100%"
                placeholder="请输入完工数量"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
           <el-col :span="12">
            <el-form-item label="生产人员">
              <el-select v-model="formData.productionPersonnel" placeholder="请输入生产人员">
                <el-option label="王浩然" value="王浩然"/>
                <el-option label="张三" value="张三"/>
                <el-option label="李四" value="李四"/>
                <el-option label="李雪妮" value="李雪妮"/>
                <el-option label="赵世豪" value="赵世豪"/>
                <el-option label="张豪" value="张豪"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在部门">
              <el-select v-model="formData.departmentSS" placeholder="请输入所在部门">
                <el-option label="包装部" value="包装部"/>
                <el-option label="生产部" value="生产部"/>
                <el-option label="酵母部" value="酵母部"/>
                <el-option label="原料部" value="原料部"/>
                <el-option label="发酵部" value="发酵部"/>
                <el-option label="采购部" value="采购部"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="addjihau">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

      <!--工序编号选择对话框 -->
      <el-dialog v-model="associatedItemDialogVisible1" width="800px" title="工序编号选择" append-to-body>
        <div class="dialog-content">
          <el-table :data="associatedItems1" highlight-current-row border size="small"
            @current-change="handleAssociatedItemChange1">
            <el-table-column type="index" label="序号" />
            <el-table-column property="processCode" label="工序编码" />
            <el-table-column property="processName" label="工序名称" />
            <el-table-column property="leader" label="负责人" />
            <el-table-column property="affiliation" label="所属部门" />
            <el-table-column property="status" label="状态" />
            <el-table-column property="remark" label="备注" />
            <el-table-column property="processTypeId" label="工序分类主键" />
            <el-table-column property="typeName" label="工序分类名称" />
          </el-table>
          
           <!-- 分页部分 -->
        <div class="demo-pagination-block">
            <el-pagination
                v-model:current-page="page.PageIndex"
                v-model:page-size="page.PageSize"
                :page-sizes="[10, 20, 30, 50]"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total.totalCount"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
        </div>
        
        <template #footer>
          <el-button @click="pickAssociatedItem1">确定</el-button>
        </template>
      </el-dialog>
  
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { ElMessage } from 'element-plus';
  import axios from 'axios';
    import { Materialread, Materialwrite } from '@/axios/axiosHelper';
  import { useRouter, useRoute } from 'vue-router';
  const router = useRouter();
  const route = useRoute();

  const formRef = ref(null);
  const currentUser = ref("admin");

  const formData = reactive({
    processCode: '',
    processName: '',
    processingOrder: '',
    processFlow: '',
    person: '',
    department: '',
    reportingTime: '',
    quantity: '',
    productionPersonnel: '',
    departmentSS: '',
    reportingpersonnel: currentUser.value,
    qualifiedQuantity: 0,
    unqualifiedQuantity: 0,
    unqualifiedReason: '',
    status: '待质检',
    isDel: true
  })

  const rules = reactive({
    processName: [
      { required: true, message: '请输入工序名称', trigger: 'blur' }
    ],
    processingOrder: [
      { required: true, message: '请输入加工顺序', trigger: 'blur' }
    ],
    processFlow: [
      { required: true, message: '请输入工艺流程', trigger: 'blur' }
    ],
    person: [
      { required: true, message: '请输入负责人', trigger: 'blur' }
    ],
    department: [
      { required: true, message: '请输入所在部门', trigger: 'blur' }
    ],
    reportingTime: [
      { required: true, message: '请选择报工时间', trigger: 'change' }
    ],
    quantity: [
      { required: true, message: '请输入完工数量', trigger: 'blur' }
    ],
    productionPersonnel: [
      { required: true, message: '请输入生产人员', trigger: 'blur' }
    ],
    departmentSS: [
      { required: true, message: '请输入所在部门', trigger: 'blur' }
    ],
    reportingpersonnel: [
      { required: true, message: '请输入报工人员', trigger: 'blur' }
    ],
    unqualifiedReason: []
  })
  
  // 保存主表单
  const addjihau = () => {
    // 表单验证
    formRef.value.validate((valid) => {
      if (valid) {
        Materialwrite.post('f-write/api/Arrival/AddQualityReportWork', formData)
         .then(response => {
            if (response.data.code === 200) {
              ElMessage.success('保存成功');
              console.log(response.data.data);
              // 这里应该跳转到列表页或执行其他操作
               router.push("/GetQualityReportWork");
            } else {
              ElMessage.error(`保存失败：${response.data.message}`);
            }
          })
         .catch(error => {
            console.error('保存出错:', error);
            ElMessage.error('保存时出现错误，请检查网络或重试');
          });
      } else {
        ElMessage.error('请填写完整且正确的表单信息');
      }
    });
  };
  
  // 重置表单
  const resetForm = () => {
    formRef.value.resetFields();
  };

  // 对话框显示状态
  const associatedItemDialogVisible1 = ref(false);
  const currentAssociatedItem1 = ref({});
  
  // 关联项目数据
  const associatedItems1 = ref([]);
  
  // 分页相关数据
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  });
  
  // 打开关联项目选择对话框
  const openAssociatedItemDialog1 = () => {
    associatedItemDialogVisible1.value = true;
    // 打开对话框时加载第一页数据
    fetchAssociatedProjects1(1, pagination.pageSize);
  };
  
  // 当前选中的关联项目行
  const handleAssociatedItemChange1 = (val) => {
    currentAssociatedItem1.value = val;
  };
  
  // 选择关联项目
  const pickAssociatedItem1 = () => {
    if (currentAssociatedItem1.value) {
      formData.processCode = currentAssociatedItem1.value.processCode; // 工序编号
      formData.processName = currentAssociatedItem1.value.processName; // 工序名称
      formData.person = currentAssociatedItem1.value.leader; // 负责人
      formData.department = currentAssociatedItem1.value.affiliation; // 所属部门
      formData.processFlow = currentAssociatedItem1.value.typeName; // 工序分类名称
      associatedItemDialogVisible1.value = false;
    }
  };

  // 定义分页对象
const page = ref({
    PageIndex: 1,
    PageSize: 50,
});

// 定义分页总数
const total = ref({
    totalCount: 0,
    totalPage: 0,
});

// // 工序列表数据
// const planList = ref([]);

// 获取工序列表
const fetchAssociatedProjects1 = () => {
    Materialread.get('f-read/api/GetProcess/GetProcedure', {
        params: {
            PageIndex: page.value.PageIndex,
            PageSize: page.value.PageSize,
        }
    }).then((res) => {
        if (res.data.code === 200) {
            associatedItems1.value = res.data.data.list || [];
            total.value.totalCount = res.data.data.totalCount || 0;
            total.value.totalPage = res.data.data.totalPage || 0;
            // 重置全选状态和选中的 ID 列表
            allChecked.value = false;
            checkedIds.value = [];
        } else {
            ElMessage.error(`获取数据失败：${res.data.message}`);
        }
    }).catch((error) => {
        handleRequestError(error);
    });
};  
 
// 分页相关方法
const handleSizeChange = (val) => {
    page.value.PageSize = val;
    fetchAssociatedProjects1();
};

const handleCurrentChange = (val) => {
    page.value.PageIndex = val;
    fetchAssociatedProjects1();
};

// 生命周期钩子：组件挂载后获取数据
onMounted(() => {
   
    fetchAssociatedProjects1();
   
});
</script>

<style scoped>
.add-quality-report {
  padding: 20px;
}

.box-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quality-form {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 22px;
}

.dialog-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
}
</style>  